<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="renderer" content="webkit" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0"
    />
    <title>分组</title>
  </head>
  <body>
    <style>
      * {padding: 0; margin: 0;}
      .wrapper{width: 100%;margin-top: 30px; display: flex;justify-content: center;align-items: center;flex-direction: column;}
      .input {display: block;width: 500px;height: 300px;font-size: 15px;resize: none; border-radius: 4px;border: 1px solid #0071e3;padding: 5px;}
      .btn {width: 260px;height: 37px;outline: none;cursor: pointer;color:#fff;background-color: #0071e3;border: none;border-radius: 4px;margin-top: 25px;}
      .result {width: 500px;text-align: left;margin-top: 25px;}
    </style>
    <div class="wrapper">
      <textarea id="input" class="input" placeholder="请输入所有人姓名，使用中文逗号隔开"></textarea>
      <button id="J-cluster" class="btn">分组</button>
      <div id="result" class="result"></div>
    </div>
    <script>
      window.onload = function () {
        function main(input) {
          const shuffle = (shuffleInput) => {
              const arr = [...shuffleInput].map(item => item.trim())
              
              let i = arr.length
              
              while (i) {
                  let j = Math.floor(Math.random() * i--)
                  ;[arr[j], arr[i]] = [arr[i], arr[j]]
              }

              return arr
          }

          const resultData = shuffle(input.split('，'))

          let resultArrays = [[], [], [], [], []]

            resultData.forEach((item, index) => {
              let targetIndex = index % 5
              resultArrays[targetIndex].push(item)
            })

            const resultHtml = resultArrays.toReversed().reduce((acc, item, index) => {
                return acc += `第${index + 1}组：${item.join('，')}</br>`
            }, '')

            document.querySelector('#result').innerHTML = resultHtml
        }

        document.querySelector('#J-cluster').onclick = function () {
          const input = document.querySelector('#input').value

          if (!input || !(input.split('，').length)) {
            alert('请输入需要分组的人员姓名')

            return
          }

          main(input)
        }
      }
    </script>
  </body>
</html>
